package cn.ppwx.crm.modules.sys.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.ppwx.crm.common.log.CrmLogger;
import cn.ppwx.crm.modules.sys.dao.PurchaseMapper;
import cn.ppwx.crm.modules.sys.entity.Purchase;
import cn.ppwx.crm.modules.sys.entity.User;
import cn.ppwx.crm.modules.sys.listener.SessionCache;


@Service
public class PurchaseService {
	
	
	@Autowired
	private PurchaseMapper  purchaseMapper;
	
	@Autowired
	private  RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	
	@Autowired
	private WorkFlowService  workFlowService;
	
	@Autowired
	private UserService  userService;
	
	

	//申请采购要货单
	public void createPurchase(Purchase purchase){
        
	  purchase.setCreateTime(new Date());
      long id = purchaseMapper.insertSelective(purchase);
      
      purchase.setPurchaseId(id);
      String purchaseBusinessNo=purchase.getClass().getSimpleName()+"-"+id;
 
      Map<String, Object> variables=new HashMap<String, Object>();
      User user = SessionCache.loginUser.get("user");
      variables.put("applyUser", user.getUserId()+"."+user.getUserName());
      
      ProcessInstance pi =runtimeService.startProcessInstanceByKey(purchase.getClass().getSimpleName().toLowerCase(), purchaseBusinessNo, variables);
      
      CrmLogger.log.info("流程实例ID："+pi.getId());
          
	}
	
	

	//经理逐级审批
	public void  manageApprove(String taskId,User user,String approveResult,String message){
		
		Map<String,Object> variables = new HashMap<String, Object>();
		variables.put("currentUserId", user.getUserId());
		variables.put("aggree", approveResult);
		workFlowService.completeTask(taskId,variables,message);
	}
	
	
	

}
